 /**
  * 公共函数库
  * @type {[type]}
  */
 var moment = require('moment');

//md5加密解决中文加密不一样的bug
exports.md5 = function(data) {
    var Buffer = require("buffer").Buffer;
    var buf = new Buffer(data);
    var str = buf.toString("binary");
    var crypto = require("crypto");
    return crypto.createHash("md5").update(str).digest("hex");
 }
//时间格式化
exports.formatDate = function (date) {
	var diffMinutes = moment().diff(date, 'minutes', true);
	var diffHours = moment().diff(date, 'hours', true);
	var dateFormatted = '';
	if (diffMinutes < 1)
		dateFormatted = '刚刚';
	else if (diffMinutes < 60)
		dateFormatted = ~~diffMinutes + '分钟之前';
	else if (diffHours < 24)
		dateFormatted = ~~diffHours + '小时之前';
	else
		dateFormatted = moment(date).format('YYYY年MM月DD日');
	return dateFormatted;
}

/**
 * ajax返回状态信息
 */
exports.returnAjax = function(status,msg,data){
	return {
			status : status,
			msg: msg,
			data : data
			};
}

//获取服务器端ip地址
exports.getIPAddresses = function () {
    var ipAddresses = [];
    var interfaces = require('os').networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                ipAddresses.push(alias.address);
            }
        }
    }
    return ipAddresses;
}
/**
 * 获取客户端ip
 * @param  {[type]} req [description]
 * @return {[type]}     [description]
 */
exports.getClientIP = function(req){ 
	return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
}